package com.sq.goodline.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sq.goodline.config.ApiConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class OssService {
	@Autowired
	ApiConfig ossConfig;
	
	/**
	 * 从oos下载指定文件并保存本地
	 * @param objectName
	 * @param localFile
	 */
	public void getFileLocal(String objectName,File localFile) {
		  CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
		  // 创建OSSClient实例。
		  ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
		  clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
		  OSS ossClient = OSSClientBuilder.create()
		  .endpoint(ossConfig.getEndpoint())
		  .credentialsProvider(credentialsProvider)
		  .clientConfiguration(clientBuilderConfiguration)
		  .region(ossConfig.getRegion())               
		  .build();
      
		  try {
			  ossClient.getObject(new GetObjectRequest(ossConfig.getBucketName(), objectName), localFile);
		  } catch (Exception oe) {
	    	   log.error("下载文件异常ObjectName：{}",objectName);
	           log.error("下载文件Oss异常:" , oe);
	      } finally {
	           if (ossClient != null) {
	               ossClient.shutdown();
	           }
	      }  
	}
	
	public byte[] getFileBytes(String objectName) {
		CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
	   	 // 创建OSSClient实例。
       ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
       clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
       OSS ossClient = OSSClientBuilder.create()
       .endpoint(ossConfig.getEndpoint())
       .credentialsProvider(credentialsProvider)
       .clientConfiguration(clientBuilderConfiguration)
       .region(ossConfig.getRegion())               
       .build();
	       
       try {
           // ossObject包含文件所在的存储空间名称、文件名称、文件元数据以及一个输入流。
           OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), objectName);
           InputStream inputStream = ossObject.getObjectContent();
           ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
           // 读取文件内容到字节数组。
           byte[] readBuffer = new byte[1024];
           int bytesRead;
           while ((bytesRead = inputStream.read(readBuffer)) != -1) {
               byteArrayOutputStream.write(readBuffer, 0, bytesRead);
           }
           // 获取最终的字节数组。
           byte[] fileBytes = byteArrayOutputStream.toByteArray();
           // 打印字节数组的长度。
           log.info("下载录音文件file size: " + fileBytes.length + " bytes");
           // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
           inputStream.close();
           byteArrayOutputStream.close();
           // ossObject对象使用完毕后必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
           ossObject.close();
           
           return fileBytes;
       } catch (Exception oe) {
    	   log.error("下载文件异常ObjectName：{}",objectName);
           log.error("下载文件Oss异常:" , oe);
           return null;
       } finally {
           if (ossClient != null) {
               ossClient.shutdown();
           }
       }  
	} 
	
	 /**
     * 文件上传oss
     * @param mp3File 本地文件绝对路径
     * @param objectName
     * @throws Exception
     */
    public boolean fileUploadOss(File mp3File,String objectName){
    	CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
   	 // 创建OSSClient实例。
       ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
       clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
       OSS ossClient = OSSClientBuilder.create()
       .endpoint(ossConfig.getEndpoint())
       .credentialsProvider(credentialsProvider)
       .clientConfiguration(clientBuilderConfiguration)
       .region(ossConfig.getRegion())               
       .build();

       try {
           // 创建PutObjectRequest对象。
           PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), objectName, mp3File);
           // 创建PutObject请求。
           PutObjectResult result = ossClient.putObject(putObjectRequest);  
           log.debug("requestId:",result.getRequestId());
           log.info("本地文件{}上传OSS完毕：{}",mp3File.getAbsolutePath(),objectName);
           
           return true;
       } catch (Exception oe) {
    	   log.error("本地文件:{},ObjectName：{}",mp3File.getAbsolutePath(),objectName);
           log.error("上传Oss异常:" , oe);
           return false;
       }finally {
           if (ossClient != null) {
               ossClient.shutdown();
           }
       }
    }
}
